package com.example.api;

/**
 * Created by hldev on 16-12-12.
 */
import com.fasterxml.classmate.TypeResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;

import static springfox.documentation.schema.AlternateTypeRules.newRule;

/**
 * Created by xiaohui on 2016/1/14.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Autowired
    private SwaggerApiSetting swaggerApiSetting;

    @Autowired
    private TypeResolver typeResolver;

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerApiSetting.isShow())
                .groupName(swaggerApiSetting.getGroup())
                .apiInfo(new springfox.documentation.service.ApiInfo(
                        swaggerApiSetting.getTitle(),
                        swaggerApiSetting.getDescription(),
                        swaggerApiSetting.getVersion(),
                        swaggerApiSetting.getTermsOfServiceUrl(),
                        new Contact(
                        swaggerApiSetting.getContact(), "", ""),
                        swaggerApiSetting.getLicense(),
                        swaggerApiSetting.getLicenseUrl()))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.web"))
                .paths(PathSelectors.any())
                .build()
                .directModelSubstitute(ZonedDateTime.class, String.class)
                .directModelSubstitute(LocalDateTime.class, String.class)
                .directModelSubstitute(LocalDate.class, String.class)
                .directModelSubstitute(LocalTime.class, String.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .pathMapping("/")
                .alternateTypeRules(
                        newRule(typeResolver.resolve(DeferredResult.class,
                                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)))
                .enableUrlTemplating(true);
    }

}